import React, { useState, useRef, useMemo } from 'react';
import { Button, Input, Tree } from 'antd';
import { EditOutlined, DeleteOutlined, SearchOutlined } from '@ant-design/icons';
import { clone as cloneDeep } from 'ramda';
import ParamSettingModal from './ParamSettingModal';
import useFlowStore from '../../hooks/flowStore';
import './VariableSetting.scss';

const VariableSetting = () => {
  const [searchValue, setSearchValue] = useState('');
  const flowContext = useFlowStore();
  const paramSettingModalRef = useRef(null);
  const treeRef = useRef(null);

  const treeData = useMemo(() => {
    console.log(flowContext.data)
    const flowVariables = flowContext.data.flowVariables.map(v => ({
      ...v,
      label: v.envName,
    }));

    return [
      {
        label: '入参变量',
        envKey: 'in',
        children: flowVariables.filter(v => v.envType === 1),
      },
      {
        label: '出参变量',
        envKey: 'out',
        children: flowVariables.filter(v => v.envType === 2),
      },
      {
        label: '中间变量',
        envKey: 'temp',
        children: flowVariables.filter(v => v.envType === 3),
      },
    ];
  }, [flowContext.data.flowVariables]);

  const maxId = useMemo(() => {
    return Math.max(...flowContext.data.flowVariables.map(v => v.id), 0);
  }, [flowContext.data.flowVariables]);

  const onAddOpen = () => {
    paramSettingModalRef.current.add(maxId + 1);
  };

  const onEditOpen = (data) => {
    paramSettingModalRef.current.edit(data);
  };

  const onAdd = (data) => {
    flowContext.update(draft => {
      const index = draft.flowVariables.findIndex(item => item.id === data.id);
      if (index === -1) {
        draft.flowVariables.push(cloneDeep(data));
      }
    });
  };

  const onEdit = (data) => {
    flowContext.update(draft => {
      const index = draft.flowVariables.findIndex(item => item.id === data.id);
      if (index > -1) {
        draft.flowVariables.splice(index, 1, data);
      }
    });
  };

  const onDelete = (data) => {
    flowContext.update(draft => {
      const index = draft.flowVariables.findIndex(item => item.envKey === data.envKey);
      if (index > -1) {
        draft.flowVariables.splice(index, 1);
      }
    });
  };

  const searchVariable = (value) => {
    treeRef.current?.filter(value);
  };

  const filterNode = (value, data) => {
    if (!value) return true;
    return data.label.includes(value) || data.envKey.includes(value);
  };

  const renderTitle = (node) => {
    if (node.children) {
      return <span className="custom-tree-node-label">{node.label}</span>;
    }
    return (
      <span className="custom-tree-node">
        <span className="custom-tree-node-label" title={node.label}>
          <span>{node.envKey}</span>
          <span className="custom-tree-node-name">{node.label}</span>
        </span>
        {node.envType === 3 && (
          <span className="tree-node-action">
            <EditOutlined onClick={() => onEditOpen(node)} />
            <DeleteOutlined onClick={() => onDelete(node)} style={{ marginLeft: 8 }} />
          </span>
        )}
      </span>
    );
  };

  return (
    <div className="flow-variable-setting">
      <div className="variable-head">
        <Button type="primary" size="small" className="add-temp-variable" onClick={onAddOpen}>
          新增中间变量
        </Button>
        <Input
          value={searchValue}
          prefix={<SearchOutlined />}
          placeholder="搜索变量"
          className="variable-search-input"
          size="small"
          onChange={(e) => {
            setSearchValue(e.target.value);
            searchVariable(e.target.value);
          }}
        />
      </div>
      <div className="variable-body">
        <Tree
          ref={treeRef}
          treeData={treeData}
          fieldNames={{ label: 'label', value: 'envKey', children: 'children' }}
          defaultExpandAll
          filterNode={filterNode}
          titleRender={renderTitle}
        />
      </div>
      <ParamSettingModal ref={paramSettingModalRef} onEdit={onEdit} onAdd={onAdd} />
    </div>
  );
};

export default VariableSetting; 